<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\AdminLogsModel;
use App\Model\AdminUserModel;
use App\Model\AdminNodeModel;
use App\Model\AdminNodeRoleModel;

//角色表
class AdminRolesModel extends Model
{
    ////定义一个表名
    protected $table = 'admin_roles';
    //定义主键
    // protected $primaryKey = 'id';

    //关联管理员
    public function users()
    {
        return $this->belongsToMany(AdminUserModel::class,'admin_role_user','role_id','user_id');
    }

    //关联权限
    public function nodes()
    {
        return $this->belongsToMany(AdminNodeModel::class,'admin_node_role','role_id','node_id')->where('admin_node.state',1);
    }

    //删除
    public function delId($id)
    {
        $res = $this->find($id);
        if($res){
            if($this->where('id', $id)->delete()){
                //删除该角色-权限
                $anrModel = new AdminNodeRoleModel;
                $anrModel->where('role_id',$id)->delete();
                //添加日志
                $msg = "删除角色【".$res['name']."】(id:".$res['id'].")";
                AdminLogsModel::addLog($msg);
                $returnArr['code'] = 1;
                $returnArr['msg'] = "删除成功";
            }else{
                $returnArr['code'] = 2;
                $returnArr['msg'] = "删除失败";
            }
        }else{
            $returnArr['code'] = 3;
            $returnArr['msg'] = "未找到指定数据或已删除";
        }
        return $returnArr;
    }
}
